"use strict";

const logger = log.getLogger("material");
const commonService = requireService("common");
const labelReplace = requireMod("common").labelReplace;
const jobs_path = getSysConfig("jobsPath");
const urlFormater = require("url").format;

/**
 * 素材配置
 * @type {Object}
 */
const MATERIAL_CONF = (getSysConfig("apiConf") || {})["@material"];

/**
 * 素材加载脚本模板
 * @type {String}
 */
const MATERIAL_TPL = commonService.read(jobs_path, "material.js", logger);

/**
 * 构造 iframe 内页或直接打开的页面
 * @param  {String} script 执行脚本
 * @return {String}        内页代码
 */
function buildPage(script) {
    return `<!DOCTYPE html><html>
            <head>
            <meta charset="utf-8"><meta name="HandheldFriendly" content="true"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"><meta name="apple-mobile-web-app-capable" content="yes" />
            <style>body,html{padding:0;margin:0;height:100%;overflow:hidden;}</style>
            </head>
            <body><script type="text/javascript">${script}</script></body>
            </html>`;
}


/**
 * 获取广告物料
 * @return {Generator}
 */
function onGet(ctx) {
    if (!MATERIAL_CONF) {
        ctx.status = 500;
        ctx.body = "MATERIAL CONFIG REQUIRED.";
        return;
    }

    // 是否是 iframe 或页面直接打开
    var isHtml = ctx.accepts("html") === "html" ? 1 : 0;
    var re = labelReplace(
        MATERIAL_TPL
        ,{
            "url": urlFormater({
                "host": MATERIAL_CONF.host
                ,"protocol": MATERIAL_CONF.protocol
                ,"pathname": MATERIAL_CONF.path
                ,"query":{
                    "id": ctx.params.id
                }
            })
            ,"write": isHtml
            ,"id": ctx.query.id || ""
        }
    );

    re = commonService.warpRespone(re);
    re = isHtml ? buildPage(re) : re;

    commonService.setHeader.call(ctx, isHtml ? "html" : "js");

    ctx.body = re;
}

module.exports = {
    "@material/:id":["GET", onGet]
}
